package com.mz.mattress.admin.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.mz.mattress.admin.interceptor.ExcelListener;
import com.mz.mattress.api.util.DateUtil;
import org.apache.commons.collections4.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

public class ExcelUtil {

    public static <T> List<T> importExcel(InputStream inputStream, Integer headRowNumber, Class<T> head, ExcelListener excelListener) {
        ExcelReaderBuilder read = EasyExcel.read(inputStream, head, excelListener);
        ExcelReaderSheetBuilder sheet = read.sheet();
        if (headRowNumber != null) {
            sheet.headRowNumber(headRowNumber);
        }
        sheet.doRead();
        return excelListener.getList();
    }


    /**
     * excel导出
     * @param response
     * @param sheetName
     * @param dataList
     */
    public static void simpleDownload(HttpServletResponse response, String sheetName, List<?> dataList) {
        simpleDownload(response, sheetName, dataList, null);
    }

    public static void simpleDownload(HttpServletResponse response, String sheetName, List<?> dataList, List<List<String>> headers) {
        if (sheetName == null) sheetName = "示例";
        if (CollectionUtils.isEmpty(dataList)) return;
        Class<?> Clazz = dataList.get(0).getClass();
        String timeStr = DateUtil.getDateTimeStr(LocalDateTime.now());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + timeStr + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Clazz).sheet(sheetName).head(headers).doWrite(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
